import {useCallback, useEffect, useState} from 'react';
import {
  ObserverButton,
  ObserverText,
  ObserverView,
  ScrollHead,
} from '../../components';
import {
  postChapterList,
  postArticleInfo,
  Collect,
  postRecommend,
  postChapterInfo,
} from '../../services';
import Header from './Header';
import ChapterList from './ChapterList';
import {observer} from 'mobx-react-lite';
import {useGlobalStore, useOtherStore, useUserInfoStore} from '../../mobx';
import {dpw12, dpw28, dpw48, HISTORY_LIST, USER_INFO} from '../../constants';
import Detail from './FirstDetail';
import {BindItem} from '../../mobx/home';
import {StyleSheet, View} from 'react-native';
import {getItem, setItem} from '../../utils';
import {useFocusEffect} from '@react-navigation/native';

export interface HeaderProps {
  Author?: string;
  AvailableTime?: string;
  BID?: number;
  CategoryList?: any[];
  ChapterCount?: number;
  CoverUrl?: string;
  Description?: string;
  ExtensionUrl?: string;
  FocusCount?: number;
  FreeFlag?: boolean;
  HasFollow?: boolean;
  LastUpdateTime?: string;
  ReadCount?: number;
  Score?: number;
  Status?: number;
  Tags?: string;
  Title?: string;
  Type?: number;
  VipFree?: boolean;
  WordCount?: number;
}

export interface ChapterItem {
  ChapterTitle: string;
  CoverUrl: string;
  FreeFlag: boolean;
  HasPurchase: boolean;
  VipFree: boolean;
  Id: number;
  Points: number;
  InsertTime: string;
}

export interface ChapterContent {
  ArticleId: number;
  AutoSubscribe: boolean;
  ChapterId: number;
  Content: string;
  FreeFlag: boolean;
  HasPurchase: boolean;
  ImageList: string[];
  NextChapter: ChapterContent;
  Points: number;
  PreviousChapter: string;
  Title: string;
  VipFree: boolean;
}

const list = [{Id: 'header'}, {Id: 'list'}, {Id: 'first'}, {Id: 'empty'}];

const DetailStore = (props: any) => {
  const {navigation, route} = props;
  const {userInfo} = useUserInfoStore();
  const {changeToastKey} = useGlobalStore();
  const {changeFoucs, foucs} = useOtherStore();
  const {bId} = route.params || {};
  const [info, setInfo] = useState<HeaderProps>();
  const [data, setData] = useState<BindItem[]>([]);
  const [chapInfo, setChapInfo] = useState<ChapterContent>();
  const [{chaplist, chapTotal, pageIndex}, setChapList] = useState<{
    chaplist: ChapterItem[];
    chapTotal: number;
    pageIndex: number;
  }>({
    chaplist: [],
    chapTotal: 0,
    pageIndex: 1,
  });
  const [{headTitle, chapTitle, btnText}, setText] = useState({
    headTitle: '',
    chapTitle: '',
    btnText: 'startReading',
  });

  // 保存浏览记录
  useFocusEffect(
    useCallback(() => {
      getItem(HISTORY_LIST).then((hisData: number[]) => {
        if (Array.isArray(hisData)) {
          if (hisData.includes(bId)) {
            setItem(HISTORY_LIST, [
              bId,
              ...hisData.filter((key: number) => key !== bId),
            ]);
          } else {
            setItem(HISTORY_LIST, [bId, ...hisData]);
          }
        } else {
          setItem(HISTORY_LIST, [bId]);
        }
      });
    }, [bId]),
  );

  useFocusEffect(
    useCallback(() => {
      const firstId = Array.isArray(chaplist) ? chaplist[0]?.Id : null;
      if (bId && firstId && userInfo?.Token) {
        postChapterInfo({
          ArticleId: bId,
          ChapterId: firstId,
          UT: userInfo?.Token,
        })
          .then((res: any) => {
            setChapInfo(res?.Data);
            setText(pret => ({...pret, chapTitle: res?.Data?.Title || ''}));
          })
          .catch(() => {});
      }
    }, [bId, chaplist, userInfo?.Token]),
  );

  useFocusEffect(
    useCallback(() => {
      postRecommend({Type: info?.Type})
        .then((res: any) => {
          setData(res?.Data);
        })
        .catch(() => {});
    }, [info?.Type, bId]),
  );

  // 跳转支付页
  const toPay = () => {
    if (navigation) {
      navigation.navigate('to-pay');
    }
  };

  // 获取章节列表
  const getChapList = useCallback(
    (idx: number, isMore?: boolean) => {
      if (userInfo?.Token && bId) {
        postChapterList({
          BID: bId,
          IsDrop: false,
          PageIndex: idx,
          PageSize: 10,
          UT: userInfo?.Token,
        })
          .then((res: any) => {
            if (Array.isArray(res?.Data)) {
              setChapList(preCl => ({
                chaplist: isMore ? [...preCl.chaplist, ...res.Data] : res.Data,
                chapTotal: res.Count,
                pageIndex: idx,
              }));
            } else {
              throw new Error('');
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    [bId, userInfo?.Token],
  );

  // 章节列表加载更多
  const onChapterListMore = useCallback(() => {
    if (chapTotal > chaplist.length) {
      getChapList(pageIndex + 1, true);
    }
  }, [getChapList, pageIndex]);

  // 签到
  const onSigin = () => {
    if (userInfo?.Token && info) {
      Collect({Id: bId, UT: userInfo?.Token})
        .then(() => {
          setInfo({...info, HasFollow: !foucs});
          changeFoucs(!foucs);
          changeToastKey(foucs ? 'unFocusSuccess' : 'focusSuccess');
        })
        .catch(() => {});
    }
  };

  // 进入阅读页
  const goDetail = (cId: number) => {
    if (navigation) {
      navigation.navigate('reader-detail', {
        chapId: cId,
        bId,
        conTitle: info?.Title,
        type: info?.Type,
        author: info?.Author,
        chapterCount: info?.ChapterCount,
      });
    }
  };

  const _renderItem = ({item}: any) => {
    if (item.Id === 'header') {
      return <Header {...info} toPay={toPay} onSigin={onSigin} foucs={foucs} />;
    }
    if (item.Id === 'list') {
      return (
        <ChapterList
          list={chaplist}
          total={chapTotal}
          goDetail={goDetail}
          onEndReached={onChapterListMore}
          bId={bId}
          {...info}
        />
      );
    }
    if (item.Id === 'first') {
      return <Detail navigation={navigation} data={data} chapInfo={chapInfo} />;
    }
    return <View style={{height: dpw48, width: '100%'}} />;
  };

  useFocusEffect(
    useCallback(() => {
      getChapList(1);
    }, [getChapList]),
  );

  useFocusEffect(
    useCallback(() => {
      if (bId && userInfo?.Token) {
        postArticleInfo({Id: bId, UT: userInfo?.Token})
          .then((res: any) => {
            if (res?.Data) {
              setInfo(res.Data);
              changeFoucs(res.Data?.HasFollow);
              setText(pret => ({...pret, headTitle: res.Data?.Title || ''}));
            } else {
              throw new Error('');
            }
          })
          .catch(() => {});
      }
    }, [bId, userInfo?.Token]),
  );

  const onViewableItemsChanged = ({changed}: any) => {
    const change = changed[0];
    if (change.key === 'list') {
      if (change.isViewable) {
        setText(pret => ({...pret, headTitle: info?.Title || ''}));
      } else {
        setText(pret => ({...pret, headTitle: chapInfo?.Title || ''}));
      }
    } else if (change.key === 'empty') {
      if (change.isViewable) {
        setText(pret => ({
          ...pret,
          btnText: 'pendReading',
          chapTitle: chapInfo?.NextChapter?.Title || chapInfo?.Title || '',
        }));
      } else {
        setText(pret => ({
          ...pret,
          btnText: 'startReading',
          chapTitle: chapInfo?.Title || '',
        }));
      }
    }
  };

  const onReaded = () => {
    navigation.navigate('reader-detail', {
      chapId:
        btnText === 'pendReading'
          ? chapInfo?.NextChapter?.ChapterId
          : chapInfo?.ChapterId,
      bId,
      conTitle: info?.Title,
      type: info?.Type,
      author: info?.Author,
      chapterCount: info?.ChapterCount,
    });
  };

  return (
    <>
      <ScrollHead
        data={list}
        title={headTitle}
        navigation={navigation}
        renderItem={_renderItem}
        onViewableItemsChanged={onViewableItemsChanged}
        initialNumToRender={2}
      />
      <ObserverView style={styles.btm} themeStyle={{borderColor: 'color_9'}}>
        <ObserverText
          size="normal"
          tKey={chapTitle}
          numberOfLines={1}
          ellipsizeMode="tail"
        />
        <ObserverButton
          style={styles.btn}
          tKey={btnText}
          type="primary"
          onPress={onReaded}
        />
      </ObserverView>
    </>
  );
};

export default observer(DetailStore);

const styles = StyleSheet.create({
  btm: {
    height: dpw48,
    position: 'absolute',
    left: 0,
    width: '100%',
    bottom: 0,
    zIndex: 99,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingLeft: dpw12,
    borderTopWidth: 1,
  },
  btn: {
    borderRadius: 0,
    paddingHorizontal: dpw28,
    paddingVertical: dpw12,
  },
});
